package storage

import (
	"context"
	"time"

	"mcp-server/internal/qdrant"
)

// VectorStorage 向量存储接口
type VectorStorage interface {
	// 初始化和连接管理
	Initialize(config *StorageConfig) error
	Close() error
	HealthCheck() error
	IsReady() bool

	// 集合管理
	CreateCollection(ctx context.Context, name string, config *CollectionConfig) error
	DeleteCollection(ctx context.Context, name string) error
	GetCollectionInfo(ctx context.Context, name string) (*CollectionInfo, error)
	ListCollections(ctx context.Context) ([]string, error)
	CollectionExists(ctx context.Context, name string) (bool, error)

	// 向量CRUD操作
	InsertVector(ctx context.Context, collection string, vector *VectorData) error
	InsertVectors(ctx context.Context, collection string, vectors []*VectorData) error
	UpdateVector(ctx context.Context, collection string, id string, vector *VectorData) error
	DeleteVector(ctx context.Context, collection string, id string) error
	DeleteVectors(ctx context.Context, collection string, ids []string) error
	GetVector(ctx context.Context, collection string, id string) (*VectorData, error)

	// 向量搜索
	SearchVectors(ctx context.Context, collection string, query *SearchQuery) (*SearchResult, error)
	SearchSimilar(ctx context.Context, collection string, vector []float32, limit int, threshold float32) (*SearchResult, error)

	// 索引管理
	CreateIndex(ctx context.Context, collection string, config *IndexConfig) error
	DeleteIndex(ctx context.Context, collection string, indexName string) error
	GetIndexInfo(ctx context.Context, collection string) ([]*IndexInfo, error)
	OptimizeIndex(ctx context.Context, collection string) error

	// 批量操作
	BatchInsert(ctx context.Context, collection string, vectors []*VectorData, batchSize int) (*BatchResult, error)
	BatchUpdate(ctx context.Context, collection string, updates []*VectorUpdate, batchSize int) (*BatchResult, error)
	BatchDelete(ctx context.Context, collection string, ids []string, batchSize int) (*BatchResult, error)

	// 统计和监控
	GetStorageStats(ctx context.Context) (*StorageStats, error)
	GetCollectionStats(ctx context.Context, collection string) (*CollectionStats, error)
}

// StorageConfig 存储配置
type StorageConfig struct {
	// Qdrant配置
	QdrantConfig *qdrant.Config `json:"qdrant_config"`

	// 连接配置
	MaxConnections    int           `json:"max_connections"`
	ConnectionTimeout time.Duration `json:"connection_timeout"`
	RequestTimeout    time.Duration `json:"request_timeout"`
	RetryAttempts     int           `json:"retry_attempts"`

	// 性能配置
	BatchSize         int  `json:"batch_size"`
	EnableCompression bool `json:"enable_compression"`
	EnableCache       bool `json:"enable_cache"`
	CacheSize         int  `json:"cache_size"`

	// 索引配置
	DefaultIndexType string                 `json:"default_index_type"`
	IndexParameters  map[string]interface{} `json:"index_parameters"`
	AutoOptimize     bool                   `json:"auto_optimize"`
	OptimizeInterval time.Duration          `json:"optimize_interval"`
}

// CollectionConfig 集合配置
type CollectionConfig struct {
	VectorSize    int                    `json:"vector_size"`
	Distance      string                 `json:"distance"`
	IndexType     string                 `json:"index_type"`
	IndexParams   map[string]interface{} `json:"index_params"`
	Replicas      int                    `json:"replicas"`
	ShardNumber   int                    `json:"shard_number"`
	OnDiskPayload bool                   `json:"on_disk_payload"`
}

// VectorData 向量数据
type VectorData struct {
	ID       string                 `json:"id"`
	Vector   []float32              `json:"vector"`
	Payload  map[string]interface{} `json:"payload"`
	Metadata *VectorMetadata        `json:"metadata,omitempty"`
}

// VectorMetadata 向量元数据
type VectorMetadata struct {
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
	Version     int       `json:"version"`
	Source      string    `json:"source"`
	ContentHash string    `json:"content_hash"`
}

// SearchQuery 搜索查询
type SearchQuery struct {
	Vector      []float32              `json:"vector"`
	Limit       int                    `json:"limit"`
	Offset      int                    `json:"offset"`
	Threshold   float32                `json:"threshold"`
	Filter      map[string]interface{} `json:"filter,omitempty"`
	WithPayload bool                   `json:"with_payload"`
	WithVector  bool                   `json:"with_vector"`
}

// SearchResult 搜索结果
type SearchResult struct {
	Hits      []*SearchHit  `json:"hits"`
	Total     int64         `json:"total"`
	QueryTime time.Duration `json:"query_time"`
}

// SearchHit 搜索命中项
type SearchHit struct {
	ID      string                 `json:"id"`
	Score   float32                `json:"score"`
	Vector  []float32              `json:"vector,omitempty"`
	Payload map[string]interface{} `json:"payload,omitempty"`
}

// IndexConfig 索引配置
type IndexConfig struct {
	Name       string                 `json:"name"`
	Type       string                 `json:"type"`
	Parameters map[string]interface{} `json:"parameters"`
}

// IndexInfo 索引信息
type IndexInfo struct {
	Name       string                 `json:"name"`
	Type       string                 `json:"type"`
	Status     string                 `json:"status"`
	Parameters map[string]interface{} `json:"parameters"`
	CreatedAt  time.Time              `json:"created_at"`
}

// CollectionInfo 集合信息
type CollectionInfo struct {
	Name         string            `json:"name"`
	VectorCount  int64             `json:"vector_count"`
	VectorSize   int               `json:"vector_size"`
	Distance     string            `json:"distance"`
	Status       string            `json:"status"`
	IndexedCount int64             `json:"indexed_count"`
	Config       *CollectionConfig `json:"config"`
	CreatedAt    time.Time         `json:"created_at"`
	UpdatedAt    time.Time         `json:"updated_at"`
}

// VectorUpdate 向量更新
type VectorUpdate struct {
	ID      string                 `json:"id"`
	Vector  []float32              `json:"vector,omitempty"`
	Payload map[string]interface{} `json:"payload,omitempty"`
}

// BatchResult 批量操作结果
type BatchResult struct {
	Total       int           `json:"total"`
	Successful  int           `json:"successful"`
	Failed      int           `json:"failed"`
	Errors      []string      `json:"errors,omitempty"`
	ProcessTime time.Duration `json:"process_time"`
}

// StorageStats 存储统计
type StorageStats struct {
	TotalCollections int64                       `json:"total_collections"`
	TotalVectors     int64                       `json:"total_vectors"`
	TotalSize        int64                       `json:"total_size_bytes"`
	MemoryUsage      int64                       `json:"memory_usage_bytes"`
	DiskUsage        int64                       `json:"disk_usage_bytes"`
	Collections      map[string]*CollectionStats `json:"collections"`
}

// CollectionStats 集合统计
type CollectionStats struct {
	Name         string    `json:"name"`
	VectorCount  int64     `json:"vector_count"`
	IndexedCount int64     `json:"indexed_count"`
	Size         int64     `json:"size_bytes"`
	LastUpdated  time.Time `json:"last_updated"`
	QueryCount   int64     `json:"query_count"`
	AvgQueryTime float64   `json:"avg_query_time_ms"`
}

// DefaultStorageConfig 创建默认存储配置
func DefaultStorageConfig() *StorageConfig {
	return &StorageConfig{
		MaxConnections:    10,
		ConnectionTimeout: 30 * time.Second,
		RequestTimeout:    60 * time.Second,
		RetryAttempts:     3,
		BatchSize:         100,
		EnableCompression: true,
		EnableCache:       true,
		CacheSize:         1000,
		DefaultIndexType:  "hnsw",
		IndexParameters: map[string]interface{}{
			"m":                   16,
			"ef_construct":        200,
			"full_scan_threshold": 10000,
		},
		AutoOptimize:     true,
		OptimizeInterval: 1 * time.Hour,
	}
}

// DefaultCollectionConfig 创建默认集合配置
func DefaultCollectionConfig(vectorSize int) *CollectionConfig {
	return &CollectionConfig{
		VectorSize: vectorSize,
		Distance:   "cosine",
		IndexType:  "hnsw",
		IndexParams: map[string]interface{}{
			"m":            16,
			"ef_construct": 200,
		},
		Replicas:      1,
		ShardNumber:   1,
		OnDiskPayload: false,
	}
}
